<template>
  <div class="project-details-plan">

    <div class="top">
      <div class="left">

        <el-form :inline="true">
          <el-form-item label="只看里程碑">
            <el-checkbox v-model="planChecked" @change="planChange"></el-checkbox>
          </el-form-item>
          <el-form-item label="甘特图">
            <el-checkbox v-model="ganttChecked" @change="ganttChange"></el-checkbox>
          </el-form-item>
        </el-form>

      </div>

      <div class="right">
        <el-select v-model="value" placeholder="请选择" @change="peopleChange">
          <el-option
            v-for="item in peopleOption"
            :key="item.member_id"
            :label="item.member_name"
            :value="item.member_id">
          </el-option>
        </el-select>

        <el-button style="margin-left: 20px" type="primary"  size="mini" @click="onKey">关键路径</el-button>

        <el-button
          v-if="((datas.status > 5 && (datas.status != 71 && datas.status != 61 && datas.status != 63  && datas.status != 52)) && isPerson) && !isDisable"
          type="primary"
          size="mini"
          @click="saveBaseLine">保存基线</el-button>

        <el-button
          v-if="(((datas.status == 6 || datas.status == 62 || datas.status == 64 || datas.status == 72) && changeTask) && isPerson) && !isDisable"
          type="primary"
          size="mini"
          @click="taskChangeClick">批量变更</el-button>
      </div>
    </div>


    <wlGantt
      v-if="ganttChecked"
      ref="wl-gantt-demo"
      align="center"
      :edit="false"
      :useCheckColumn="false"
      use-real-time
      use-check-column
      use-index-column
      :end-date="endDate"
      :start-date="startDate"
      date-type="monthAndDay"
      :data="planChecked?tableData2:tableData"
      :contextMenuOptions="contextMenuOptions"
      :expandRowKeys="expandRowKeys"
      @selection-change="selectionChange"
      @expand-change="expandChange"
      @timeChange="timeChange"
      @taskRemove="taskRemove"
      @preChange="preChange"
      @taskAdd="taskAdd"
      @row-click="tableRowClick"
    >

      <template>

        <el-table-column
          fixed
          width="100"
          label="工期（天）"
        >
          <template slot-scope="scope">
            {{scope.row.duration}}
            <!--              <el-input v-model="scope.row.name"></el-input>-->
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="任务状态"
          width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">未启动</span>
            <span v-if="scope.row.status == 1">进行中</span>
            <span v-if="scope.row.status == 2">暂停</span>
            <!--        <span v-if="datas.status == 3">延期</span>-->
            <span v-if="scope.row.status == 4">待验收</span>
            <span v-if="scope.row.status == 5">验收不通过</span>
            <span v-if="scope.row.status == 6">已完成</span>
            <div v-if="scope.row.delay_day" style="color: red">延期({{scope.row.delay_day}}天)</div>
          </template>
        </el-table-column>

        <el-table-column
          fixed
          width="100"
          label="负责人"
        >
          <template slot-scope="scope">
            {{scope.row.person_in_charge.member_name}}
            <!--              <el-input v-model="scope.row.name"></el-input>-->
          </template>
        </el-table-column>

      </template>

    </wlGantt>

    <div v-else>

      <!--        <task-list-view :datas="planChecked?tableData2:tableData" :project-id="datas.id" :project-name="datas.project_name" :members="members"></task-list-view>-->

      <el-table
        size="medium"
        :data="planChecked?tableData2:tableData"
        border
        row-key="id"
        @row-click="tableRowClick"
        default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        style="width: 100%">
        <el-table-column
          align="center"
          type="index"
          width="50px"
          label="序号">
        </el-table-column>
        <el-table-column
          header-align="center"
          min-width="200"
          label="里程碑/任务名称">
          <template slot-scope="scope">

            <span v-if="(!scope.row.children || !scope.row.children.length) && scope.row.level == 1" style="padding-left: 25px">  </span>
            <span>{{scope.row.task_name}}</span>

          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="duration"
          label="工期（天）">
        </el-table-column>
        <el-table-column
          align="center"
          prop="foreground_task_name"
          label="前置任务">
        </el-table-column>
        <el-table-column
          align="center"
          label="任务进度">
          <template slot-scope="scope">
            <span>{{scope.row.task_progress}}%</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="已耗时">
          <template slot-scope="scope">
            <span>{{dealTimeConsuming(scope.row)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="person"
          label="负责人">
          <template slot-scope="scope">
            <div v-if="scope.row.person_in_charge && scope.row.person_in_charge.member_id">
              {{scope.row.person_in_charge.member_name}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="任务状态">
          <template slot-scope="scope">
            <span v-if="scope.row.status == 0">未启动</span>
            <span v-if="scope.row.status == 1">进行中</span>
            <span v-if="scope.row.status == 2">暂停</span>
            <!--        <span v-if="datas.status == 3">延期</span>-->
            <span v-if="scope.row.status == 4">待验收</span>
            <span v-if="scope.row.status == 5">验收不通过</span>
            <span v-if="scope.row.status == 6">已完成</span>
            <div v-if="scope.row.delay_day" style="color: red">延期({{scope.row.delay_day}}天)</div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="startDate"
          label="计划开始日期">
          <template slot-scope="scope">

            <span>{{scope.row.startDate}}</span>

          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="endDate"
          label="计划结束日期">
          <template slot-scope="scope">

            <span>{{scope.row.endDate}}</span>

          </template>
        </el-table-column>

        <el-table-column
          align="center"
          label="实际开始日期">
          <template slot-scope="scope">

            <span>{{scope.row.real_start_date ? dateFormat1('yyyy-mm-dd',scope.row.real_start_date) : ""}}</span>

          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="实际结束日期">
          <template slot-scope="scope">

            <span>{{scope.row.real_end_date ? dateFormat1('yyyy-mm-dd',scope.row.real_end_date) : ""}}</span>

          </template>
        </el-table-column>

        <el-table-column
          align="center"
          prop="days"
          label="参与人">
          <template slot-scope="scope">
            <div v-if="scope.row.task_member && scope.row.task_member.length > 0">
              <el-popover
                placement="top-start"
                width="100"
                trigger="hover">
                <div>
                  <div v-for="item in scope.row.task_member" style="padding-bottom: 5px">
                    <i class="el-icon-user">{{  item.member_name}}</i>
                  </div>
                </div>
                <i slot="reference" class="el-icon-user">{{scope.row.task_member.length}}</i>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="阶段性评审">
          <template slot-scope="scope">
            <span>{{scope.row.periodical_review?'是':'否'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="强制验收">
          <template slot-scope="scope">
            <span>{{scope.row.mandatory_check?'是':'否'}}</span>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <el-dialog title="关键路径" width="1400px" :visible.sync="keyDialog">
      <wlGantt
        :edit="false"
        :check-source="false"
        :autoGanttDateType="false"
        :useCheckColumn="false"
        :use-check-column="false"
        use-index-column
        :end-date="endDate"
        :start-date="startDate"
        date-type="monthAndDay"
        :data="keyData"
        :contextMenuOptions="contextMenuOptions"
        :expandRowKeys="expandRowKeys"
      >

        <template>

          <el-table-column
            align="center"
            fixed
            prop="duration"
            width="100"
            label="工期（天）"
          >
          </el-table-column>

          <el-table-column
            align="center"
            fixed
            width="100"
            label="负责人"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.person_in_charge && scope.row.person_in_charge.member_id">
                {{scope.row.person_in_charge.member_name}}
              </div>
            </template>
          </el-table-column>

          <el-table-column
            align="center"
            fixed
            label="参与人"
            width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.task_member && scope.row.task_member.length > 0">
                <el-popover
                  placement="top-start"
                  width="100"
                  trigger="hover">
                  <div>
                    <div v-for="item in scope.row.task_member" style="padding-bottom: 5px">
                      <i class="el-icon-user">{{ item.member_name}}</i>
                    </div>
                  </div>
                  <i slot="reference" class="el-icon-user">{{scope.row.task_member.length}}</i>
                </el-popover>
              </div>
            </template>
          </el-table-column>

        </template>

      </wlGantt>
    </el-dialog>

  </div>
</template>

<script>
    import taskListView from './taskListView/index'

    export default {
        name: "planView",
        components:{taskListView},
        props:{
            datas:{
                type:Object,
                default:function () {
                    return{
                        member:[],
                        project_task:[]
                    }
                }
            },
            isDisable:{
                type: Boolean,
                default:function () {
                    return false
                }
            },
            changeTask:{
                type:Boolean,
                default:true,
            }
        },
        watch: {
            datas: {
                handler(newval,oldval){
                    if (newval){
                        this.setData(newval);
                    }
                },
                deep: true,
                immediate: true
            }
        },
        data:function () {
            return{
                isPerson:false,
                selected: [], // 选中数据
                contextMenuOptions: [
                    { label: "任务名称", prop: "name" },
                    { label: "计划开始时间", prop: "startDate" },
                    { label: "计划结束时间", prop: "endDate" },
                ],
                expandRowKeys: ["1"],
                planChecked:false,
                ganttChecked:false,
                keyChecked:false,
                value:'',

                tableData:[],
                tableData2:[],

                startDate:'',
                endDate:'',

                id:1,

                members:[],

                originalData:[],

                peopleOption:[
                    {
                        member_id:"",
                        member_name:"全部"
                    }
                ],

                keyDialog:false,
                keyData:[]
            }
        },
        mounted:function(){

            this.setData(this.datas);
            this.checkPerson();
            this.peopleOption = this.peopleOption.concat(this.datas.member)
        },
        methods:{
            taskChangeClick:function(){
                this.$router.push({name:'projectManagementTaskChange',query:{id:this.datas.id}})
            },
            dealTimeConsuming:function(row){
                let str = "0.00%"
                // if (row.real_start_date){
                //     let date = new Date(row.real_start_date).getTime()
                //     let date2 = new Date().getTime()
                //     if (row.real_end_date){
                //         date2 = new Date(row.real_end_date).getTime()
                //     }
                //
                //     let day = 60*60*24*1000
                //     let time = (date2 - date)/day + 1
                //     let num = Number(time.toFixed(0))
                //     let x = num/(row.duration | 0)*100
                //     str = x.toFixed(2) + "%"
                // }

                if (row.real_start_date){
                    let date = new Date(row.real_start_date.replace(/-/g,'/'))
                    let date2 = new Date()
                    let y = 0
                    if (row.real_end_date){
                        date2 = new Date(row.real_end_date.replace(/-/g,'/'))
                        y = 1
                    }
                    var endTime = (date2.getTime() / 1000) - (date.getTime() / 1000);
                    var timeDay = parseInt(endTime / 60 / 60 / 24) + y;        //相差天数
                    if (date.toLocaleDateString() == date2.toLocaleDateString()){
                        timeDay = 0
                    }else {
                        timeDay = timeDay == 0 ? 1 : timeDay
                    }
                    let x = timeDay/(row.duration | 0)*100
                    str = x.toFixed(2) + "%"
                }

                return str;
            },
            checkPerson:function(){
                if (this.datas.project_person_in_charge_id == this.$store.getters.userInfo.user.id){
                    this.isPerson = true;
                    return
                }
                this.isPerson = false
            },
            onKey:function(){
                this.$api.TASK_CAL_LINE({data:this.tableData}).then(res=>{
                    if (res.code == 200){
                        this.keyDialog = true;
                        if (res.data){
                            res.data.forEach(item=>{
                                item.children = []
                                item.startDate = item.start_date
                                item.endDate = item.end_date
                                item.name = item.task_name
                            })
                            this.keyData = res.data
                        }

                    }else{
                        this.$message.error(res.msg)
                    }

                })
            },
            saveBaseLine:function(){
                this.$api.PROJECT_START_BASELINE_CREATE(this.datas.id).then(res=>{
                    if (res.code == 200){
                        this.$message.success("保存成功")
                    }else {
                        this.$message.error(res.msg)
                    }
                })
            },
            tableRowClick:function(row, column, event){
                // console.log(row, column, event)
                if (this.datas.status > 5 && this.datas.status != 52){
                    this.$router.push({name:'projectManagementTaskDetail',query:{id:row.id,t:new Date().getTime()}});
                }
            },
            setData:function(newval){

                if(newval){
                    let data = newval;
                    if (data.plan_start_time != ''){
                        this.startDate = this.dealDateStr(new Date(data.plan_start_time.replace(/-/g,'/')))
                    }
                    if (data.plan_end_time != ''){
                        this.endDate = this.dealDateStr(new Date(data.plan_end_time.replace(/-/g,'/')))
                    }

                    if (data.project_task){
                        this.originalData = [...data.project_task];
                        // this.tableData = [...data.project_task];
                        for (let i = 0; i < this.originalData.length; i++){
                            this.dealInitData(this.originalData[i],[]);
                        }
                        this.tableData = [...this.originalData];
                    }
                    if (data.member){
                        this.members = data.member;
                    }
                }
            },
            /**
             * 时间发生更改
             * row: Object 当前行数据c
             */
            timeChange(row) {
                //console.log("时间修改:", row);
            },
            //
            /**
             * 前置任务发生更改
             * row: Object 当前行数据
             * oldval: [String, Array] 前置修改前的旧数据
             * handle: Boolean 是否用户编辑产生的改变
             */
            preChange(row, oldval, handle) {
                //console.log("前置修改:", row, oldval, handle);
            },
            // 数表展开行
            expandChange(row, expanded) {
                //console.log("展开行:", row, expanded);
            },
            // 多选选择
            selectionChange(val) {
                //console.log("多选：", val);
            },
            // 删除任务
            taskRemove(item) {
                //console.log("删除任务：", item);
            },
            // 添加任务
            taskAdd(item) {
                //console.log("添加任务：", item);
                // 非懒加载方式直接设置子数据
                /* this.$set(
                  item,
                  "children",
                  item.children.concat([
                    {
                      pid: item.id,
                      id: "###",
                      name: "一轮新月",
                      startDate: "2019-10-11",
                      endDate: "2019-10-19"
                    }
                  ])
                ); */
                this.$refs["wl-gantt-demo"].loadTreeAdd(item.id, [
                    {
                        pid: item.id,
                        id: "###",
                        name: "一轮新月",
                        startDate: "2019-10-11",
                        endDate: "2019-10-19",
                    },
                ]);
            },
            planChange:function(value){
                if (value){
                    this.tableData2 = [];
                    for (let i = 0; i < this.tableData.length; i++){
                        let data = {...this.tableData[i]};
                        data.children = [];
                        this.tableData2.push(data)
                    }
                }
            },
            ganttChange:function(value){

            },
            keyChange:function(){

            },
            dealDateStr:function(date){
                let year = date.getFullYear();
                let month = date.getMonth() + 1;
                let day = date.getDate();
                if (month < 10){
                    month = "0" + month
                }
                if (day < 10){
                    day = "0" + day;
                }

                return year + "-" + month + "-" + day
            },
            dealInitData:function(data,persons){
                let arr = [...persons]
                data.name = data.task_name;
                data.startDate = this.dealDateStr(new Date(data.start_date.replace(/-/g,'/')));
                data.endDate = this.dealDateStr(new Date(data.end_date.replace(/-/g,'/')));
                let index = arr.findIndex(a=>a == data.person_in_charge.member_id)
                if (index == -1){
                    arr.push(data.person_in_charge.member_id)
                }
                data.persons = [...arr];

                if (data.children){
                    for (let i = 0; i < data.children.length; i++){
                        this.dealInitData(data.children[i],arr);
                    }
                }
            },
            peopleChange:function () {

                if (!this.value) {
                    this.tableData = [...this.originalData];
                } else {
                    this.tableData = [];

                    // for (let i = 0; i < this.originalData.length; i++){
                    //     let data = {...this.originalData[i]};
                    //
                    //     if (data.person_in_charge && data.person_in_charge.member_id == this.value){
                    //         if (data.children && data.children.length > 0){
                    //             data.children = this.sss(data.children,this.value)
                    //         }
                    //     }
                    //     this.tableData.push(data);
                    // }

                    this.tableData = this.sss(this.originalData,this.value);
                }

                this.tableData2 = [];
                for (let i = 0; i < this.tableData.length; i++){
                    let data = {...this.tableData[i]};
                    data.children = [];
                    this.tableData2.push(data)
                }
            },
            sss:function (list,id) {
                let arr = []
                for (let i = 0; i < list.length; i++){
                    let data = {...list[i]};

                    if (data.person_in_charge){
                        let index = data.task_member ? data.task_member.findIndex(a=>a.member_id == id) : -1
                        if (data.person_in_charge.member_id == this.value || index != -1){
                            if (data.children && data.children.length > 0){
                                data.children = this.sss(data.children,id)
                            }
                            arr.push(data);
                        }
                    }
                }
                return arr
            }
        }
    }
</script>

<style lang="scss">
  @import "@/assets/scss/views/projectManagement/list/details/plan.scss";
</style>
